//
//  EMConversationsViewController.m
//  ChatDemo-UI3.0
//
//  Created by XieYajie on 2019/1/8.
//  Copyright © 2019 XieYajie. All rights reserved.
//

#import "EMConversationsViewController.h"
#import "EMChatViewController.h"
#import "EMRealtimeSearch.h"
#import "PellTableViewSelect.h"
#import "EMSearchResultController.h"
#import "EMInviteGroupMemberViewController.h"
#import "EMCreateGroupViewController.h"
#import "EMInviteFriendViewController.h"
#import "EMNotificationViewController.h"
#import "EMConversationUserDataModel.h"
#import "UserInfoStore.h"

#import "EMDateHelper.h"
#import <EaseDateHelper.h>

@interface EMConversationsViewController()
<EaseConversationsViewControllerDelegate
, EMSearchControllerDelegate
, EMGroupManagerDelegate
>

@property (nonatomic, strong) UIButton *addImageBtn;
@property (nonatomic, strong) EMInviteGroupMemberViewController *inviteController;
@property (nonatomic, strong) EaseConversationsViewController *easeConvsVC;
@property (nonatomic, strong) EaseConversationViewModel *viewModel;
@property (nonatomic, strong) UINavigationController *resultNavigationController;
@property (nonatomic, strong) EMSearchResultController *resultController;



//test
@property (nonatomic,strong) dispatch_queue_t workQueue;
@property (nonatomic,weak)EMConversationsViewController *p_weakSelf;


@property (nonatomic,strong)NSDateFormatter *dateFormatter;

@end

@implementation EMConversationsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:0.99 green:0.98 blue:0.97 alpha:1];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTableView) name:CHAT_BACKOFF object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTableView) name:GROUP_LIST_FETCHFINISHED object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTableView) name:USERINFO_UPDATE object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(refreshConversations)
                                                 name:USER_PUSH_CONFIG_UPDATE object:nil];
    [EMClient.sharedClient.groupManager addDelegate:self delegateQueue:dispatch_get_main_queue()];
    [self _setupSubviews];
    if (![EMDemoOptions sharedOptions].isFirstLaunch) {
        [EMDemoOptions sharedOptions].isFirstLaunch = YES;
        [[EMDemoOptions sharedOptions] archive];
        [self refreshTableViewWithData];
    }
}

- (void)refreshConversations {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
    });
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
}

- (void)dealloc
{
    [EMClient.sharedClient.groupManager removeDelegate:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)_setupSubviews
{
    self.view.backgroundColor = [UIColor clearColor];
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = NSLocalizedString(@"conversation", nil);
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.font = [UIFont systemFontOfSize:18];
    [self.view addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.view).offset(EMVIEWTOPMARGIN + 35);
        make.height.equalTo(@25);
    }];
    
    self.addImageBtn = [[UIButton alloc]init];
    [self.addImageBtn setImage:[UIImage imageNamed:@"icon-add"] forState:UIControlStateNormal];
    [self.addImageBtn addTarget:self action:@selector(moreAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.addImageBtn];
    [self.addImageBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.equalTo(@35);
        make.centerY.equalTo(titleLabel);
        make.right.equalTo(self.view).offset(-16);
    }];
    
    {
        UIButton *button = UIButton.new;
        [button setTitle:@"TEST" forState:UIControlStateNormal];
        [button setTitleColor:UIColor.grayColor forState:UIControlStateNormal];
        [button addTarget:self action:@selector(testAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(@60);
            make.height.equalTo(@44);
            make.centerY.equalTo(titleLabel);
            make.left.equalTo(self.view).offset(-0);
        }];
    }
    
    self.viewModel = [[EaseConversationViewModel alloc] init];
    self.viewModel.canRefresh = YES;
    self.viewModel.badgeLabelPosition = EMAvatarTopRight;
    
    self.easeConvsVC = [[EaseConversationsViewController alloc] initWithModel:self.viewModel];
    self.easeConvsVC.delegate = self;
    [self addChildViewController:self.easeConvsVC];
    [self.view addSubview:self.easeConvsVC.view];
    [self.easeConvsVC.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLabel.mas_bottom).offset(15);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
    [self _updateConversationViewTableHeader];
}





//- (void)autoLoginDidCompleteWithError:(EMError *)aError{
//}


int i = 0;


#define MULT 10


long fetchMax(long value){
    long currentValue = value;
    long result = 0;
    {
        long base = currentValue;
        if(base < 20){
            result = ceil(base * 1.2);
        }else if (base < 100){
            result = ceil(base + base / 6);
            result = (base / 5 + 1) * 5;
        }else{
            long multiple = 1;
            long tipValue = base + base / 6.5;
            do{
                tipValue /= 10;
                multiple *= 10;
            }while(tipValue > 100);
            result = (tipValue + 1) * multiple;
        }
    }
    return result;
}

int inRoom = 0;

int testIndex = 0;

/**
*  用格式:时间获取正确时区的时间字符串
*
*  @param format 时间格式 @"yyyy-MM-dd HH:mm:ss"
*  @param date   时间
*
*  @return 时间字符串
*/
- (NSString *)dateStringWithTimestamp:(long long)timestamp{
    NSString *dateString = [self.dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:timestamp]];
    return  dateString;
}

- (void)outputMessage:(EMChatMessage *)message prefix:(NSString *)prefix {
    NSString *content = @"[非TXT类型消息]";
    if (message.body.type == EMMessageBodyTypeText){
        content = ((EMTextMessageBody *)message.body).text;
        if (content.length > 20) {
            content = [content substringToIndex:20];
        }
    }
    NSLog(@"%@id[%@]时间戳[%@]from[%@]内容:[%@]",prefix,message.messageId,[self dateStringWithTimestamp:message.timestamp / 1000],message.from,content);

}

- (NSString *)unicodeFromText:(NSString *)string{
    NSUInteger length = [string length];
    NSMutableString *str = [NSMutableString stringWithCapacity:0];
    for (int i = 0;i < length; i++){
        NSMutableString *s = [NSMutableString stringWithCapacity:0];
        unichar _char = [string characterAtIndex:i];
        // 判断是否为英文和数字
        if (_char <= '9' && _char >='0'){
            [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i,1)]];
        }else if(_char >='a' && _char <= 'z'){
            [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i,1)]];
        }else if(_char >='A' && _char <= 'Z')
        {
            [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i,1)]];
        }else{
            // 中文和字符
            [s appendFormat:@"\\u%x",[string characterAtIndex:i]];
            // 不足位数补0 否则解码不成功
            if(s.length == 4) {
                [s insertString:@"00" atIndex:2];
            } else if (s.length == 5) {
                [s insertString:@"0" atIndex:2];
            }
        }
        [str appendFormat:@"%@", s];
    }
    return str;
}


- (NSString *)textFromUnicode:(NSString *)unicodeStr{
    NSString *tempStr1=[unicodeStr stringByReplacingOccurrencesOfString:@"\\u"withString:@"\\U"];
    NSString *tempStr2=[tempStr1 stringByReplacingOccurrencesOfString:@"\""withString:@"\\\""];
    NSString *tempStr3=[[@"\"" stringByAppendingString:tempStr2]stringByAppendingString:@"\""];
    NSData *tempData=[tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    
    NSString* returnStr = [NSPropertyListSerialization propertyListWithData:tempData options:NSPropertyListImmutable format:NULL error:NULL];
//    NSString* returnStr = [NSPropertyListSerialization propertyListFromData:tempData
//                                                         mutabilityOption:NSPropertyListImmutable
//                                                                   format:NULL
//                                                         errorDescription:NULL];
     
    return [returnStr stringByReplacingOccurrencesOfString:@"\\r\\n"withString:@"\n"];
}
- (BOOL)logResult_action:(NSString *)action error:(EMError *)error{
    if(error){
        NSLog(@"test ---(%@) - 失败(%ld)%@",action,(long)error.code,error.errorDescription);
        NSLog(@"test end : failure =======================================");
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:[NSString stringWithFormat:@"test ---(%@) - 失败(%ld)%@",action,(long)error.code,error.errorDescription] preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *clearAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alertController addAction:clearAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
        NSLog(@"test ---(%@) - 成功",action);
    }
    return error;
}
NSString *testGroupId = @"需要填入你当前这个群组的groupid";
NSMutableArray *groupMessages;
- (void)looper_fetchGroupMessageAcks:(EMChatMessage *)message completion:(void (^) (void))completion{
    __weak typeof(self) weakSelf = self;
    [EMClient.sharedClient.chatManager asyncFetchGroupMessageAcksFromServer:message.messageId groupId:testGroupId startGroupAckId:nil pageSize:10 completion:^(EMCursorResult<EMGroupMessageAck *> * _Nullable aResult, EMError * _Nullable error, int totalCount) {
        NSLog(@"==================");
        NSLog(@"==================");
        NSLog(@"==================");
        NSLog(@"输出消息信息:");
        NSString *content = @"[非TXT类型消息]";
        if (message.body.type == EMMessageBodyTypeText){
            content = ((EMTextMessageBody *)message.body).text;
        }
        NSLog(@"消息id[%@]已读用户数[%d]内容[%@]",message.messageId,message.groupAckCount,content);
        if([weakSelf logResult_action:@"获取消息的已读回执" error:error]){
            return;
        }
        NSLog(@"从服务器获取群消息的已读回执情况:");
        NSLog(@"block回调中totalCount参数:%d",totalCount);
        for (EMGroupMessageAck *ack in aResult.list) {
            NSLog(@"群组消息id:%@",ack.messageId);
            NSLog(@"群组消息已读回执id:%@",ack.readAckId);
            NSLog(@"群组消息发送者:%@",ack.from);
            NSLog(@"群组消息内容:%@",ack.content);
            NSLog(@"群组消息已读人数:%d",ack.readCount);
            NSLog(@"群组消息回执发送的 Unix 时间戳:%lld",ack.timestamp);
        }
        NSLog(@"==================");
        NSLog(@"==================");
        NSLog(@"==================");
        
        [groupMessages removeLastObject];
        if(!groupMessages.count){
            completion();
            return;
        }
        [weakSelf looper_fetchGroupMessageAcks:groupMessages.lastObject completion:completion];
    }];

    
}

- (void)startFetchGroupMessageAcks{
    [self looper_fetchGroupMessageAcks:groupMessages.lastObject completion:^{
        NSLog(@"全部消息已输出完成");
        NSLog(@"全部消息已输出完成");
        NSLog(@"全部消息已输出完成");
    }];
}

//这是一个测试按钮点击事件
- (void)testAction:(UIButton *)sender{
    __weak typeof(self) weakSelf = self;
    NSString *partyUsername = @"";

    
    
    
    
    
    
    partyUsername = @"yy3";
    
    EMFileMessageBody *body = [[EMFileMessageBody alloc] initWithData:NSData.new displayName:@"test"];
    
    EMChatMessage *message = [[EMChatMessage alloc] initWithConversationID:partyUsername body:body ext:@{@"aaa":@"aaa"}];
    
    
    
    
    
    [EMClient.sharedClient.chatManager sendMessage:message progress:^(int progress) {
            
        } completion:^(EMChatMessage * _Nullable message, EMError * _Nullable error) {
            if (error) {
                NSLog(@"发送消息失败");
            }else{
                NSLog(@"发送消息成功");
            }
        }];

//    EMConversation *conversation = EMClient.sharedClient.chatManager conversation
    
    
    
    
    //发一条消息
//    partyUsername = @"yy3";
//    EMTextMessageBody *body = [EMTextMessageBody.alloc initWithText:@"杨剑测试---发一条消息后删除"];
//    EMChatMessage *message = [EMChatMessage.alloc initWithConversationID:partyUsername body:body ext:nil];
//    NSString *tempMessageId = message.messageId;
//    [EMClient.sharedClient.chatManager sendMessage:message progress:nil completion:^(EMChatMessage * _Nullable message, EMError * _Nullable error) {
//        if([self logResult_action:@"发送了一条消息" error:error]){
//            return;
//        }
//        NSLog(@"消息id[%@]",message.messageId);
//        
//        EMConversation *conversation = [EMClient.sharedClient.chatManager getConversationWithConvId:partyUsername];
//        
//        if (!conversation){
//            NSLog(@"会话不存在");
//            return;
//        }
//        EMError *deleteError;
//        [conversation deleteMessageWithId:message.messageId error:&deleteError];
//        if([weakSelf logResult_action:@"删除本地消息,使用的是服务器返回的消息id" error:deleteError]){
//        }
//        
//        [conversation deleteMessageWithId:tempMessageId error:&deleteError];
//        if([weakSelf logResult_action:@"删除本地消息,使用的是发送前生成的id" error:deleteError]){
//        }
//        
//        
//        
//        
//    }];
    
    //立刻删除
    
    
    
//    partyUsername = @"love135421077327531";
//    EMFetchServerMessagesOption *op = [EMFetchServerMessagesOption new];
//    op.direction = EMMessageSearchDirectionUp;
//    [EMClient.sharedClient log:@"test-log-从服务器获取消息"];
//    
//    
//    [[EMClient sharedClient].chatManager fetchMessagesFromServerBy:partyUsername conversationType:EMConversationTypeChat cursor:nil pageSize:50 option:op completion:^(EMCursorResult<EMChatMessage *> *result, EMError *error) {
//        if([weakSelf logResult_action:@"从服务器获取消息" error:error]){
//            return;
//        }
//        [EMClient.sharedClient log:@"test-log-从服务器获取消息成功"];
//        
//        for (EMChatMessage *message in result.list) {
//            NSString *content = @"[非TXT类型消息]";
//            if (message.body.type == EMMessageBodyTypeText){
//                content = ((EMTextMessageBody *)message.body).text;
//            }
//            NSLog(@"消息id[%@]时间戳[%ld]from-to[%@-%@]内容[%@]",message.messageId,message.timestamp,message.from,message.to,content);
//        }
//
//        
//        [EMClient.sharedClient log:@"test-log-===================================end"];
//        [EMClient.sharedClient log:@"test-log-===================================end"];
//        [EMClient.sharedClient log:@"test-log-===================================end"];
//    }];
#if 0
    
    
    
    NSString *groupId = @"206174159962115";
//    EMClient.sharedClient.groupManager group
    EMGroup *group = [EMGroup groupWithId:groupId];
    [EMClient.sharedClient log:@"杨剑输出===EMGroup *group = [EMGroup groupWithId:groupId[206174159962115]];"];
    [EMClient.sharedClient log:[NSString stringWithFormat:@"杨剑输出===group.isBlocked = %d",group.isBlocked]];
    
    [EMClient.sharedClient.groupManager getGroupSpecificationFromServerWithId:groupId fetchMembers:true completion:^(EMGroup * _Nullable aGroup, EMError * _Nullable error) {
        if([weakSelf logResult_action:@"groupManager/获取群详情" error:error]){
            return;
        }
        [EMClient.sharedClient log:@"杨剑输出===getGroupSpecificationFromServerWithId:[206174159962115]"];
        [EMClient.sharedClient log:[NSString stringWithFormat:@"杨剑输出===group.isBlocked = %d",aGroup.isBlocked]];
    }];
    
    
//    [EMClient.sharedClient log:@"杨剑输出===开始屏蔽某群聊206174159962115,当前username:yy2"];
//    [EMClient.sharedClient log:@"杨剑输出===开始屏蔽某群聊206174159962115,当前username:yy2"];
//    [EMClient.sharedClient log:@"杨剑输出===开始屏蔽某群聊206174159962115,当前username:yy2"];
//
//
//    [[EMClient sharedClient].groupManager blockGroup:groupId completion:^(EMGroup * _Nullable aGroup, EMError * _Nullable error) {
//        if([weakSelf logResult_action:@"groupManager blockGroup屏蔽群消息" error:error]){
//            return;
//        }
//        NSLog(@"成功");
//        [EMClient.sharedClient log:@"杨剑输出===结束屏蔽某群聊206174159962115,当前username:yy2"];
//        [EMClient.sharedClient log:@"杨剑输出===结束屏蔽某群聊206174159962115,当前username:yy2"];
//        [EMClient.sharedClient log:@"杨剑输出===结束屏蔽某群聊206174159962115,当前username:yy2"];
//    }];

#endif
    
    
    
#if 0
    [EMClient.sharedClient log:@"test-log-===================================start"];
    [EMClient.sharedClient log:@"test-log-===================================start"];
    [EMClient.sharedClient log:@"test-log-===================================start"];
    NSString *partyUsername = @"yy1";
    NSArray <EMConversation *> *sessions1 = [[EMClient sharedClient].chatManager getAllConversations:NO];
    for (EMConversation *session in sessions1) {
        if ([session.conversationId isEqualToString:partyUsername]) {
            NSLog(@"test-log-找到会话,获取会话未读数 = %d", session.unreadMessagesCount);
        }
    }
    
    [EMClient.sharedClient log:@"test-log-将要发送会话已读回执"];
    [EMClient.sharedClient.chatManager ackConversationRead:partyUsername completion:^(EMError * _Nullable aError) {
        [EMClient.sharedClient log:@"test-log-已经发送会话已读回执"];
        [EMClient.sharedClient log:@"test-log-本地获取会话,并在本地标记已读markAllMessagesAsRead"];
        EMConversation *conversation = [[EMClient sharedClient].chatManager getConversationWithConvId:partyUsername];
        EMError *error = nil;
        [conversation markAllMessagesAsRead:&error];
        [EMClient.sharedClient log:[NSString stringWithFormat:@"test-log-本地标记已读完成error = %@", error]];
        [EMClient.sharedClient log:[NSString stringWithFormat:@"test-log-已经发送已读回执,本地已经标记已读.获取会话未读数 = %d", conversation.unreadMessagesCount]];
        
        EMFetchServerMessagesOption *op = [EMFetchServerMessagesOption new];
        op.direction = EMMessageSearchDirectionDown;
        [EMClient.sharedClient log:@"test-log-从服务器获取消息"];
        [[EMClient sharedClient].chatManager fetchMessagesFromServerBy:partyUsername conversationType:EMConversationTypeChat cursor:nil pageSize:50 option:op completion:^(EMCursorResult<EMChatMessage *> *result, EMError *error) {
            if([weakSelf logResult_action:@"从服务器获取消息" error:error]){
                return;
            }
            [EMClient.sharedClient log:@"test-log-从服务器获取消息成功"];
            NSArray <EMConversation *> *sessions2 = [[EMClient sharedClient].chatManager getAllConversations:NO];
            for (EMConversation *session in sessions2) {
                if ([session.conversationId isEqualToString:partyUsername]) {
                    [EMClient.sharedClient log:[NSString stringWithFormat:@"test-log-重新从服务器获取消息之后.获取会话未读数 = %d", session.unreadMessagesCount]];
                }
            }
            [EMClient.sharedClient log:@"test-log-===================================end"];
            [EMClient.sharedClient log:@"test-log-===================================end"];
            [EMClient.sharedClient log:@"test-log-===================================end"];
        }];
    }];
    return;
    
#endif
#if 0


    groupMessages = NSMutableArray.new;
    EMConversation *groupConversation = [EMClient.sharedClient.chatManager getConversation:testGroupId type:EMConversationTypeGroupChat createIfNotExist:true];
    __weak typeof(self) weakSelf = self;
    [groupConversation loadMessagesStartFromId:nil count:20 searchDirection:EMMessageSearchDirectionUp completion:^(NSArray<EMChatMessage *> * _Nullable aMessages, EMError * _Nullable aError) {
        if([weakSelf logResult_action:@"从本地数据库获取一组群聊消息" error:aError]){
            return;
        }
        [groupMessages addObjectsFromArray:aMessages];
        [weakSelf startFetchGroupMessageAcks];
    }];
    
    
    
    
    
    
    
    
    
    
    
    
    
    EMTextMessageBody *body = [EMTextMessageBody.alloc initWithText:@"杨剑测试---测试表情回复"];
    EMChatMessage *message = [EMChatMessage.alloc initWithConversationID:partyUsername body:body ext:nil];

    [EMClient.sharedClient.chatManager sendMessage:message progress:nil completion:^(EMChatMessage * _Nullable message, EMError * _Nullable error) {
        if([self logResult_action:@"发送了一条消息" error:error]){
            return;
        }
        NSLog(@"消息id[%@]",message.messageId);
        
        //发送消息成功之后,对这条消息做一个表情回复
        
        [EMClient.sharedClient.chatManager addReaction:@"做了个表情回复啊啊啊" toMessage:message.messageId completion:^(EMError * _Nullable error) {
            if([self logResult_action:@"做了个表情回复" error:error]){
                return;
            }
            NSLog(@"消息id[%@]",message.messageId);
        }];
    }];

    return;
    
    
    
    
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        EMFetchServerMessagesOption *opt = [[EMFetchServerMessagesOption alloc] init];
        [EMClient.sharedClient.chatManager fetchMessagesFromServerBy:@"" conversationType:EMConversationTypeGroupChat cursor:nil pageSize:30 option:opt completion:^(EMCursorResult<EMChatMessage *> * _Nullable result, EMError * _Nullable aError) {
            if ([self logResult_action:@"获取历史消息" error:aError]){
                NSLog(@"错误");
                return;
            }
            for (EMChatMessage *message in result.list) {
                NSString *content = @"[非TXT类型消息]";
                if (message.body.type == EMMessageBodyTypeText){
                    content = ((EMTextMessageBody *)message.body).text;
                }
                NSLog(@"输出消息 : [%@]内容:[%@]",message.messageId,content);
            }
        }];

    });
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [EMClient.sharedClient.chatManager asyncFetchHistoryMessagesFromServer:@"" conversationType:EMConversationTypeGroupChat startMessageId:nil pageSize:20 completion:^(EMCursorResult<EMChatMessage *> * _Nullable aResult, EMError * _Nullable aError) {
            if ([self logResult_action:@"获取历史消息" error:aError]){
                NSLog(@"错误");
                return;
            }
            for (EMChatMessage *message in aResult.list) {
                NSString *content = @"[非TXT类型消息]";
                if (message.body.type == EMMessageBodyTypeText){
                    content = ((EMTextMessageBody *)message.body).text;
                }
                NSLog(@"输出消息 : [%@]内容:[%@]",message.messageId,content);
            }
        }];
    });
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [EMClient.sharedClient.chatManager asyncFetchHistoryMessagesFromServer:@"" conversationType:EMConversationTypeGroupChat startMessageId:nil fetchDirection:EMMessageSearchDirectionUp pageSize:20 completion:^(EMCursorResult<EMChatMessage *> * _Nullable aResult, EMError * _Nullable aError) {
            if ([self logResult_action:@"获取历史消息" error:aError]){
                NSLog(@"错误");
                return;
            }
            for (EMChatMessage *message in aResult.list) {
                NSString *content = @"[非TXT类型消息]";
                if (message.body.type == EMMessageBodyTypeText){
                    content = ((EMTextMessageBody *)message.body).text;
                }
                NSLog(@"输出消息 : [%@]内容:[%@]",message.messageId,content);
            }
        }];
    });

//    [EMClient.sharedClient.chatManager fetchMessagesFromServerBy:nil conversationType:EMConversationTypeGroupChat cursor:nil pageSize:30 option:opt completion:^(EMCursorResult<EMChatMessage *> * _Nullable result, EMError * _Nullable aError) {
//        for (EMChatMessage *message in result.list) {
//            NSString *content = @"[非TXT类型消息]";
//            if (message.body.type == EMMessageBodyTypeText){
//                content = ((EMTextMessageBody *)message.body).text;
//            }
//            NSLog(@"输出消息 : [%@]内容:[%@]",message.messageId,content);
//        }
//    }];

    
    
    
    
    
    
    NSString *timeString;
    timeString = [EMDateHelper formattedTimeFromTimeInterval:1713713626593];
    NSLog(@"[EMDateHelper - 1713713626593][%@]",timeString);

    timeString = [EaseDateHelper formattedTimeFromTimeInterval:1713713626593];
    NSLog(@"[EaseDateHelper - 1713713626593][%@]",timeString);

    
    
    
    
    
    ;return;
//    [EMClient.sharedClient.chatManager asyncFetchHistoryMessagesFromServer:@"yy2" conversationType:EMConversationTypeChat   startMessageId:nil pageSize:20 completion:^(EMCursorResult *aResult, EMError *aError) {
//        
//        
//        for (EMChatMessage *message in aResult.list) {
//            NSString *content = @"[非TXT类型消息]";
//            if (message.body.type == EMMessageBodyTypeText){
//                content = ((EMTextMessageBody *)message.body).text;
//            }
//            NSLog(@"输出消息 : [%@]内容:[%@]",message.messageId,content);
//        }
//    }];
//    EMFetchServerMessagesOption *opt = [[EMFetchServerMessagesOption alloc] init];
//    
//    [EMClient.sharedClient.chatManager fetchMessagesFromServerBy:@"yy2" conversationType:EMConversationTypeChat cursor:nil pageSize:30 option:opt completion:^(EMCursorResult<EMChatMessage *> * _Nullable result, EMError * _Nullable aError) {
//        for (EMChatMessage *message in result.list) {
//            NSString *content = @"[非TXT类型消息]";
//            if (message.body.type == EMMessageBodyTypeText){
//                content = ((EMTextMessageBody *)message.body).text;
//            }
//            NSLog(@"输出消息 : [%@]内容:[%@]",message.messageId,content);
//        }
//    }];
    
    
    return;


    return;
    //1.获取一个会话
    partyUsername = @"yy2";
    EMConversation *conversation = [EMClient.sharedClient.chatManager getConversation:partyUsername type:EMConversationTypeChat createIfNotExist:true];
    
    EMError *error = nil;
    NSArray <EMChatMessage *>*messages = nil;
    //1.先从本地获取
    
    
    EMCmdMessageBody *cmdBody = [EMCmdMessageBody.alloc initWithAction:@"test"];
    cmdBody.isDeliverOnlineOnly = false;
    EMTextMessageBody *textBody = [EMTextMessageBody.alloc initWithText:@"test"];
    EMCustomMessageBody *customBody = [EMCustomMessageBody.alloc initWithEvent:@"test" customExt:nil];
    
    
//    EMChatMessage *message = [EMChatMessage.alloc initWithConversationID:partyUsername body:cmdBody ext:nil];
    
    [EMClient.sharedClient.chatManager sendMessage:message progress:nil completion:^(EMChatMessage * _Nullable message, EMError * _Nullable error) {
        if([self logResult_action:@"发送了一条消息" error:error]){
            return;
        }
        NSLog(@"消息id[%@]",message.messageId);
//        [EMClient.sharedClient.chatManager recallMessageWithMessageId:message.messageId completion:^(EMError * _Nullable aError) {
//            if([self logResult_action:@"撤回了一条消息" error:aError]){
//                return;
//            }
//        }];
    }];
    
    
    
    
    return;
    messages = [conversation loadMessagesStartFromId:nil count:20 searchDirection:EMMessageSearchDirectionUp];
    NSLog(@"第一次本地获取结果:");
    for(EMChatMessage *message in messages){
        NSLog(@"消息[%@]已读[%d]",message.messageId,message.isRead);
    }
    
    NSLog(@"第二次服务器获取结果:");
    messages = [EMClient.sharedClient.chatManager fetchHistoryMessagesFromServer:partyUsername conversationType:EMConversationTypeChat startMessageId:nil pageSize:20 error:&error].list;
    if ([self logResult_action:@"从服务器获取消息" error:error]){
        return;
    }
    
    for(EMChatMessage *message in messages){
        NSLog(@"消息[%@]已读[%d]",message.messageId,message.isRead);
    }
    
    NSLog(@"第三次本地获取结果:");
    messages = [conversation loadMessagesStartFromId:nil count:20 searchDirection:EMMessageSearchDirectionUp];
    for(EMChatMessage *message in messages){
        NSLog(@"消息[%@]已读[%d]",message.messageId,message.isRead);
    }

    
    
    
    
    
    
    //240140565938186
    [EMClient.sharedClient.groupManager joinPublicGroup:@"240140565938186" completion:^(EMGroup * _Nullable aGroup, EMError * _Nullable aError) {
        if([self logResult_action:@"加入一个群" error:aError]){
        }
    }];
    
    
    
    return;
    self.dateFormatter = [[NSDateFormatter alloc] init];
    [self.dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];//

    NSString *groupid = @"wyq6";
//    NSString *partyUsername = @"248";
    
    {
        EMFetchServerMessagesOption *fetchOption = EMFetchServerMessagesOption.new;
//        fetchOption.from = partyUsername;
//        fetchOption.direction = EMMessageSearchDirectionUp;
        fetchOption.startTime   = 1707094800000;
        fetchOption.endTime     = 1707105600000;
        [EMClient.sharedClient.chatManager fetchMessagesFromServerBy:groupid conversationType:EMConversationTypeChat cursor:nil pageSize:20 option:fetchOption completion:^(EMCursorResult<EMChatMessage *> * _Nullable result, EMError * _Nullable aError) {
            if([self logResult_action:@"获取指定消息" error:aError]) return;
            NSLog(@"==============================");
            NSLog(@"==============================");
            for (EMChatMessage *message in result.list) {
                [self outputMessage:message prefix:@"[获取定向]输出消息:"];
            }
            NSLog(@"==============================");
            NSLog(@"==============================");
        }];

    }
    return;
    
    
    [EMClient.sharedClient.chatManager asyncFetchHistoryMessagesFromServer:groupid conversationType:EMConversationTypeGroupChat startMessageId:nil pageSize:50 completion:^(EMCursorResult<EMChatMessage *> * _Nullable aResult, EMError * _Nullable aError) {
        if([self logResult_action:@"获取所有消息" error:aError]) return;
        NSLog(@"==============================");
        NSLog(@"==============================");
        for (EMChatMessage *message in aResult.list) {
            [self outputMessage:message prefix:@"[获取所有]输出消息:"];
        }
        NSLog(@"==============================");
        NSLog(@"==============================");

        
    }];

    
#endif
    
    
    
#if 0

    //1.获取一个会话
    NSString *partyUsername = @"yy2";
    EMConversation *conversation = [EMClient.sharedClient.chatManager getConversation:partyUsername type:EMConversationTypeChat createIfNotExist:true];
    //2.根据会话获取20条消息,并遍历输出
    EMError *error = nil;
    NSArray <EMChatMessage *>*messages = [EMClient.sharedClient.chatManager fetchHistoryMessagesFromServer:partyUsername conversationType:EMConversationTypeChat startMessageId:nil pageSize:20 error:&error].list;
    if ([self logResult_action:@"获取消息" error:error]){
        return;
    }

    for (EMChatMessage *message in messages) {
        NSString *content = @"[非TXT类型消息]";
        if (message.body.type == EMMessageBodyTypeText){
            content = ((EMTextMessageBody *)message.body).text;
        }
        NSLog(@"输出消息<删除前> : [%@]内容:[%@]",message.messageId,content);
    }
    
    //3.删除其中一条消息,这里删除倒数第二条消息(如果不存在很多消息,则删除最后一条消息)
    NSString *removeMessageid = messages.lastObject.messageId;
    if (messages.count - 2 < 0) {
    }else{
        removeMessageid = messages[messages.count - 2].messageId;
    }
    
    //4.删除之前预先输出下这条消息以及id
    for (EMChatMessage *message in messages) {
        if (![message.messageId isEqualToString:removeMessageid]) {
            continue;
        }
        NSString *content = @"[非TXT类型消息]";
        if (message.body.type == EMMessageBodyTypeText){
            content = ((EMTextMessageBody *)message.body).text;
        }
        NSLog(@"[%@]内容:[%@]",message.messageId,content);
    }

    //5.执行删除
    [conversation removeMessagesFromServerMessageIds:@[removeMessageid] completion:^(EMError * _Nullable aError) {
        if ([self logResult_action:@"删除消息" error:aError]){
            return;
        }
        //6.重新获取消息,看是否还能获取到已删除的消息
        
        //7.判断是否有之前删除过的消息
        bool isExist = false;
        EMError *error = nil;
        NSArray <EMChatMessage *>*messages = [EMClient.sharedClient.chatManager fetchHistoryMessagesFromServer:partyUsername conversationType:EMConversationTypeChat startMessageId:nil pageSize:20 error:&error].list;
        if ([self logResult_action:@"获取消息" error:error]){
            return;
        }
        for (EMChatMessage *message in messages) {
            NSString *content = @"[非TXT类型消息]";
            if (message.body.type == EMMessageBodyTypeText){
                content = ((EMTextMessageBody *)message.body).text;
            }
            NSLog(@"输出消息<删除后> : [%@]内容:[%@]",message.messageId,content);
            if([message.messageId isEqualToString:removeMessageid]) {
                isExist = true;
            }
        }
        NSLog(@"是否存在?[%@]",isExist ? @"是" : @"否");
    }];
    
#endif
#if 0
    NSArray <EMGroup *>*groups = [[EMClient sharedClient].groupManager getJoinedGroups];
    for (EMGroup *g in groups) {
        NSLog(@"[%@][%@]",g.groupId,g.groupName);
    }
    return;

    //设置推送通知方式为 `MentionOnly`。
    EMSilentModeParam *param = [[EMSilentModeParam alloc]initWithParamType:EMSilentModeParamTypeRemindType];
    param.remindType = EMPushRemindTypeMentionOnly;//只有 "@我" 的消息才会收到提醒
    param.remindType = EMPushRemindTypeNone;//完全不提醒
    
    
    NSString *testConversationID = @"";
    EMConversationType conversationType;
    
    //单聊:
    testConversationID = @"这里填写一个单聊的对方的id";
    conversationType = EMConversationTypeChat;
    
    
    //群聊:
    testConversationID = @"这里填写一个群id";
    conversationType = EMConversationTypeGroupChat;

    // 异步方法
    [EMClient.sharedClient.pushManager setSilentModeForConversation:testConversationID
                                                   conversationType:conversationType 
                                                             params:param 
                                                         completion:^(EMSilentModeResult *aResult, EMError *aError) {
        if (aError) {//这里是设置失败
            NSLog(@"setSilentModeForConversation error---%@",aError.errorDescription);
        }
    }];
    
    
    [EMClient.sharedClient.pushManager getSilentModeForConversations:@[testConversationID] completion:^(NSDictionary<NSString *,EMSilentModeResult *> * _Nullable aResult, EMError * _Nullable aError) {
       
        EMSilentModeResult *result = aResult[testConversationID];
        NSLog(@"%ld",result.remindType);
        
    }];
    
    
    
    return;
    
    
    
    
    
    
    

    EMConversation *conversation = [EMClient.sharedClient.chatManager getConversation:@"yy1" type:EMConversationTypeChat createIfNotExist:true];
//    NSString *event = [NSString stringWithFormat:@"第2次"];
//    EMCustomMessageBody *body = [[EMCustomMessageBody alloc] initWithEvent:event customExt:@{@"body-ext":event}];
    
    
    EMImageMessageBody *body = [[EMImageMessageBody alloc] initWithLocalPath:@"" displayName:@"image.jpg"];
    
    
    
    EMChatMessage *message = [[EMChatMessage alloc] initWithConversationID:@"yy1" body:body ext:@{@"msg-ext":@"这是一条自定义消息"}];
    message.status = EMMessageStatusDelivering;
    NSInteger timestamp = NSDate.date.timeIntervalSince1970 * 1000;
    message.timestamp = timestamp;
    message.localTime = timestamp;
    EMError *error;
    [conversation insertMessage:message error:&error];
    NSLog(@"%@,%ld",error.errorDescription,error.code);
    
    
    return;
//    EMSilentModeParam *param = [[EMSilentModeParam alloc] initWithParamType:EMSilentModeParamTypeRemindType];
//    param.remindType = EMPushRemindTypeNone;
//    [EMClient.sharedClient.pushManager setSilentModeForAll:param completion:^(EMSilentModeResult * _Nullable aResult, EMError * _Nullable aError) {
//    }];
    
    
    
    
    
    
    
    
    
    [EMClient.sharedClient.presenceManager fetchPresenceStatus:@[@"714",@"test0004"] completion:^(NSArray<EMPresence *> * _Nullable presences, EMError * _Nullable error) {
        if ([self logResult_action:@"获取用户在线状态" error:error]){
            return;
        }
        NSMutableString *fmtString = NSMutableString.new;
        for (EMPresence *presence in presences) {
            [fmtString appendString:presence.publisher];
            [fmtString appendString:@"\n"];
            NSLog(@"=================");
            NSLog(@"%@ 状态如下:",presence.publisher);
            for (EMPresenceStatusDetail *sdt in presence.statusDetails) {
                [fmtString appendFormat:@"  %@[%ld]",sdt.device,sdt.status];
                NSLog(@"==[%@][%ld]",sdt.device,sdt.status);
            }
            NSLog(@"=================");
        }
        
//        UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"" message:fmtString preferredStyle:UIAlertControllerStyleAlert];
//        [controller addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//        }]];
//        [self presentViewController:controller animated:true completion:^{
//        }];
    }];
    
    
    
    
    
    
    return;
    EMGroupOptions *options = EMGroupOptions.new;
    options.IsInviteNeedConfirm = false;
    NSArray <NSString *>*usernames = @[@"wyq1",@"hfp",@"cyt",@"lp"];
    
    [EMClient.sharedClient.groupManager createGroupWithSubject:@"test测试" description:@"abc" invitees:usernames message:@"来加入测试群组" setting:options completion:^(EMGroup * _Nullable aGroup, EMError * _Nullable aError) {
        if([self logResult_action:@"创建群组" error:aError]){
            return;
        }
        
        
        
        
        
        [EMClient.sharedClient log:@"杨剑标记========开始========="];
        [EMClient.sharedClient.groupManager getGroupSpecificationFromServerWithId:aGroup.groupId fetchMembers:true completion:^(EMGroup * _Nullable aGroup, EMError * _Nullable aError) {
            NSString *str1 = [NSString stringWithFormat:@"实际成员数 \t\t\t%ld",aGroup.memberList.count + 1];//加1是加上群主
            NSString *str2 = [NSString stringWithFormat:@"参数occupantsCount给到的值是\t %ld",aGroup.occupantsCount];
            NSLog(@"%@", str1);
            NSLog(@"%@", str2);
            [EMClient.sharedClient log:str1];
            [EMClient.sharedClient log:str2];
            [EMClient.sharedClient log:@"杨剑标记========结束========="];
            NSLog(@"=========================");
            NSLog(@"=========================");

        }];
        
    }];
    
    
    
    
    
    
    
    return;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self loop];
    });
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2* NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        NSLog(@"执行取消");
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(loop) object:nil];
    });
    
    
//    EMOptions *options = [EMOptions optionsWithAppkey:@"<your appkey>"];
//    options.autoAcceptGroupInvitation = true;
//
//    //config options ...
//
//    [EMClient.sharedClient initializeSDKWithOptions:options];
    
//    EMGroupOptions *options = [[EMGroupOptions alloc] init];
//    options.IsInviteNeedConfirm = true;
    //config options ...

    [EMClient.sharedClient.groupManager createGroupWithSubject:@"群组名称"
                                                   description:@"群组描述。"
                                                      invitees:@[]  //群组成员，不包括创建者自己。
                                                       message:@"message"
                                                       setting:options
                                                    completion:^(EMGroup * _Nullable aGroup, EMError * _Nullable aError) {
        NSLog(@"group id : %@",aGroup.groupId);
    }];
    
#endif

}

- (void)loop{
    NSLog(@"===index:%d",testIndex++);
//    [self performSelector:@selector(loop) withObject:nil afterDelay:0.5f];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        [self performSelector:@selector(loop) withObject:nil afterDelay:0.5f];
    });
}



- (void)sendMSG{
    NSString *event = [NSString stringWithFormat:@"第1次"];
    EMCustomMessageBody *body = [[EMCustomMessageBody alloc] initWithEvent:event customExt:@{@"body-ext":event}];
    EMChatMessage *message = [[EMChatMessage alloc] initWithConversationID:@"yy4" body:body ext:@{@"msg-ext":@"这是一条自定义消息"}];
    NSString *localid = message.messageId;
    [EMClient.sharedClient.chatManager sendMessage:message progress:nil completion:^(EMChatMessage * _Nullable message, EMError * _Nullable error) {
        NSString *serverid = message.messageId;
        [self logResult_action:@"发消息" error:error];
        NSLog(@"===================%@-%@",localid,serverid);
    }];

}



int __sendCustomIndex = 0;


- (void)testSendMessageToGroup{
    __weak typeof(self) weakSelf = self;
    NSString *groupid = @"219299513958401";
    NSString *event = [NSString stringWithFormat:@"第%d次",__sendCustomIndex];
    EMCustomMessageBody *body = [[EMCustomMessageBody alloc] initWithEvent:event customExt:@{@"body-ext":event}];
    EMChatMessage *message = [[EMChatMessage alloc] initWithConversationID:groupid body:body ext:@{@"msg-ext":@"这是一条自定义消息"}];
    message.chatType = EMChatTypeGroupChat;
    [EMClient.sharedClient.chatManager sendMessage:message progress:nil completion:^(EMChatMessage * _Nullable message, EMError * _Nullable error) {
        
        if ([self logResult_action:[NSString stringWithFormat:@"群组自定义消息发送%d",__sendCustomIndex] error:error]){
            
        }
        __sendCustomIndex ++;
        if (__sendCustomIndex > 100){
            __sendCustomIndex = 0;
            return;
        }
        [weakSelf testSendMessageToGroup];
    }];

}


- (void)testCreateGroup_completionHandler:(void (^_Nullable)(EMGroup *_Nullable group, EMError *_Nullable error))completionHandler{
    EMGroupOptions *options = [[EMGroupOptions alloc] init];
    // 设置群组最大成员数量。
    options.maxUsers = 200;
    // 设置 `IsInviteNeedConfirm` 为 `YES`，则邀请用户入群需要用户确认。
//    options.IsInviteNeedConfirm = NO;
    // 设置群组类型。此处示例为成员可以邀请用户入群的私有群组。
    options.style = EMGroupStylePublicOpenJoin;
    NSArray *members = @[@"89",@"88",@"87",@"86",@"85"];
    // 调用 `createGroupWithSubject` 创建群组。同步方法，异步方法见 [EMGroupManager createGroupWithSubject:description:invitees:message:setting:completion:]
    [[EMClient sharedClient].groupManager createGroupWithSubject:@"环信IM测试小组1" description:@"" invitees:members message:@"message" setting:options completion:^(EMGroup *aGroup, EMError *aError) {
        completionHandler( aGroup, aError);
    }];
}

- (void)testSendMessageToGroup_message:(EMMessage *)message completionHandler:(void (^)(EMChatMessage * _Nullable message, EMError * _Nullable error))completionHandler{
    [EMClient.sharedClient.chatManager sendMessage:message progress:nil completion:^(EMChatMessage * _Nullable message, EMError * _Nullable error) {
        completionHandler(message,error);
    }];
}

- (void)testFetchConversation:(NSString *)conversationid{
    NSLog(@"传入的会话id == (%@)",conversationid);
    EMConversation *conversation = [EMClient.sharedClient.chatManager getConversationWithConvId:conversationid];
    NSLog(@"新获取到的会话对象 == (%@)",conversation);
    NSLog(@"新获取到的会话id == (%@)",conversation.conversationId);
    NSLog(@"新获取到的会话类型 == (%ld)",(long)conversation.type);
}


- (void)_updateConversationViewTableHeader {
    self.easeConvsVC.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectZero];
    self.easeConvsVC.tableView.tableHeaderView.backgroundColor = [UIColor colorWithRed:242.0/255.0 green:242.0/255.0 blue:242.0/255.0 alpha:1];
    UIControl *control = [[UIControl alloc] initWithFrame:CGRectZero];
    control.clipsToBounds = YES;
    control.layer.cornerRadius = 18;
    control.backgroundColor = UIColor.whiteColor;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(searchButtonAction)];
    [control addGestureRecognizer:tap];
    
    [self.easeConvsVC.tableView.tableHeaderView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.easeConvsVC.tableView);
        make.width.equalTo(self.easeConvsVC.tableView);
        make.top.equalTo(self.easeConvsVC.tableView);
        make.height.mas_equalTo(52);
    }];
    
    [self.easeConvsVC.tableView.tableHeaderView addSubview:control];
    [control mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_offset(36);
        make.top.equalTo(self.easeConvsVC.tableView.tableHeaderView).offset(8);
        make.bottom.equalTo(self.easeConvsVC.tableView.tableHeaderView).offset(-8);
        make.left.equalTo(self.easeConvsVC.tableView.tableHeaderView.mas_left).offset(17);
        make.right.equalTo(self.easeConvsVC.tableView.tableHeaderView).offset(-16);
    }];
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"search"]];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
    label.font = [UIFont systemFontOfSize:16];
    label.text = NSLocalizedString(@"search", nil);
    label.textColor = [UIColor colorWithRed:204.0/255.0 green:204.0/255.0 blue:204.0/255.0 alpha:1];
    [label setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
    UIView *subView = [[UIView alloc] init];
    [subView addSubview:imageView];
    [subView addSubview:label];
    [control addSubview:subView];
    
    [imageView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(15);
        make.left.equalTo(subView);
        make.top.equalTo(subView);
        make.bottom.equalTo(subView);
    }];
    
    [label mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(imageView.mas_right).offset(3);
        make.right.equalTo(subView);
        make.top.equalTo(subView);
        make.bottom.equalTo(subView);
    }];
    
    [subView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(control);
    }];
}

- (void)_setupSearchResultController
{
    __weak typeof(self) weakself = self;
    self.resultController.tableView.rowHeight = 70;
    self.resultController.tableView.rowHeight = UITableViewAutomaticDimension;
    [self.resultController setCellForRowAtIndexPathCompletion:^UITableViewCell *(UITableView *tableView, NSIndexPath *indexPath) {
        NSString *cellIdentifier = @"EaseConversationCell";
        EaseConversationCell *cell = (EaseConversationCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [EaseConversationCell tableView:tableView cellViewModel:weakself.viewModel];
        }
        
        NSInteger row = indexPath.row;
        EaseConversationModel *model = [weakself.resultController.dataArray objectAtIndex:row];
        cell.model = model;
        return cell;
    }];
    [self.resultController setCanEditRowAtIndexPath:^BOOL(UITableView *tableView, NSIndexPath *indexPath) {
        return YES;
    }];
    [self.resultController setTrailingSwipeActionsConfigurationForRowAtIndexPath:^UISwipeActionsConfiguration *(UITableView *tableView, NSIndexPath *indexPath) {
        EaseConversationModel *model = [weakself.resultController.dataArray objectAtIndex:indexPath.row];
        UIContextualAction *deleteAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive
                                                                                   title:NSLocalizedString(@"deleteConversation", nil)
                                                                                 handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL))
        {
            [weakself.resultController.tableView setEditing:NO];
            int unreadCount = [[EMClient sharedClient].chatManager getConversationWithConvId:model.easeId].unreadMessagesCount;
            
            [[EMClient sharedClient].chatManager deleteServerConversation:model.easeId conversationType:model.type isDeleteServerMessages:YES completion:^(NSString *aConversationId, EMError *aError) {
                if (aError) {
                    [weakself showHint:aError.errorDescription];
                }
            }];
            
            [[EMClient sharedClient].chatManager deleteConversation:model.easeId isDeleteMessages:YES completion:^(NSString *aConversationId, EMError *aError) {
                if (!aError) {
                    [[EMTranslationManager sharedManager] removeTranslationByConversationId:model.easeId];
                    [weakself.resultController.dataArray removeObjectAtIndex:indexPath.row];
                    [weakself.resultController.tableView reloadData];
                    if (unreadCount > 0 && weakself.deleteConversationCompletion) {
                        weakself.deleteConversationCompletion(YES);
                    }
                }
            }];
        }];
        UIContextualAction *topAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleNormal
                                                                                title:!model.isTop ? NSLocalizedString(@"top", nil) : NSLocalizedString(@"canceltop", nil)
                                                                              handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL))
        {
            [weakself.resultController.tableView setEditing:NO];
            [model setIsTop:!model.isTop];
            [weakself.easeConvsVC refreshTable];
        }];
        UISwipeActionsConfiguration *actions = [UISwipeActionsConfiguration configurationWithActions:@[deleteAction,topAction]];
        actions.performsFirstActionWithFullSwipe = NO;
        return actions;
    }];
    [self.resultController setDidSelectRowAtIndexPathCompletion:^(UITableView *tableView, NSIndexPath *indexPath) {
        NSInteger row = indexPath.row;
        EaseConversationModel *model = [weakself.resultController.dataArray objectAtIndex:row];
        weakself.resultController.searchBar.text = @"";
        [weakself.resultController.searchBar resignFirstResponder];
        weakself.resultController.searchBar.showsCancelButton = NO;
        [weakself searchBarCancelButtonAction:nil];
        [weakself.resultNavigationController dismissViewControllerAnimated:YES completion:nil];
        //系统通知
        if ([model.easeId isEqualToString:EMSYSTEMNOTIFICATIONID]) {
            EMNotificationViewController *controller = [[EMNotificationViewController alloc] initWithStyle:UITableViewStylePlain];
            [weakself.navigationController pushViewController:controller animated:YES];
            return;
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:CHAT_PUSHVIEWCONTROLLER object:model.easeId];
    }];
}

- (void)refreshTableView
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if(self.view.window)
            [self.easeConvsVC refreshTable];
    });
}

- (void)refreshTableViewWithData
{
    __weak typeof(self) weakself = self;
    [[EMClient sharedClient].chatManager getConversationsFromServer:^(NSArray *aCoversations, EMError *aError) {
        if (!aError && [aCoversations count] > 0) {
            [weakself.easeConvsVC.dataAry removeAllObjects];
            [weakself.easeConvsVC.dataAry addObjectsFromArray:aCoversations];
            [weakself.easeConvsVC refreshTable];
        }
    }];
}

#pragma mark - searchButtonAction

- (void)searchButtonAction
{
    if (self.resultNavigationController == nil) {
        self.resultController = [[EMSearchResultController alloc] init];
        self.resultController.delegate = self;
        self.resultNavigationController = [[UINavigationController alloc] initWithRootViewController:self.resultController];
        [self.resultNavigationController.navigationBar setBackgroundImage:[[UIImage imageNamed:@"navBarBg"] stretchableImageWithLeftCapWidth:10 topCapHeight:10] forBarMetrics:UIBarMetricsDefault];
        [self _setupSearchResultController];
    }
    [self.resultController.searchBar becomeFirstResponder];
    self.resultController.searchBar.showsCancelButton = YES;
    self.resultNavigationController.modalPresentationStyle = 0;
    [self presentViewController:self.resultNavigationController animated:YES completion:nil];
}

#pragma mark - moreAction

- (void)moreAction
{
    [PellTableViewSelect addPellTableViewSelectWithWindowFrame:CGRectMake(self.view.bounds.size.width-200, self.addImageBtn.frame.origin.y, 185, 104) selectData:@[NSLocalizedString(@"createGroup", nil),NSLocalizedString(@"newContact", nil)] images:@[@"icon-创建群组",@"icon-添加好友"] locationY:30 - (22 - EMVIEWTOPMARGIN) action:^(NSInteger index){
        if(index == 0) {
            [self createGroup];
        } else if (index == 1) {
            [self addFriend];
        }
    } animated:YES];
}

//创建群组
- (void)createGroup
{
    self.inviteController = nil;
    self.inviteController = [[EMInviteGroupMemberViewController alloc] init];
    __weak typeof(self) weakself = self;
    [self.inviteController setDoneCompletion:^(NSArray * _Nonnull aSelectedArray) {
        EMCreateGroupViewController *createController = [[EMCreateGroupViewController alloc] initWithSelectedMembers:aSelectedArray];
        createController.inviteController = weakself.inviteController;
        [createController setSuccessCompletion:^(EMGroup * _Nonnull aGroup) {
            [[NSNotificationCenter defaultCenter] postNotificationName:CHAT_PUSHVIEWCONTROLLER object:aGroup];
        }];
        [weakself.navigationController pushViewController:createController animated:YES];
    }];
    
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:self.inviteController];
    navController.modalPresentationStyle = 0;
    [self presentViewController:navController animated:YES completion:nil];
}

//添加好友
- (void)addFriend
{
    EMInviteFriendViewController *controller = [[EMInviteFriendViewController alloc] init];
    [self.navigationController pushViewController:controller animated:YES];
}

#pragma mark - EMSearchControllerDelegate

- (void)searchBarWillBeginEditing:(UISearchBar *)searchBar
{
    self.resultController.searchKeyword = nil;
}

- (void)searchBarCancelButtonAction:(UISearchBar *)searchBar
{
    [[EMRealtimeSearch shared] realtimeSearchStop];
    
    if ([self.resultController.dataArray count] > 0) {
        [self.resultController.dataArray removeAllObjects];
    }
    [self.resultController.tableView reloadData];
    [self.easeConvsVC refreshTabView];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self.view endEditing:YES];
}

- (void)searchTextDidChangeWithString:(NSString *)aString
{
    self.resultController.searchKeyword = aString;
    
    __weak typeof(self) weakself = self;
    [[EMRealtimeSearch shared] realtimeSearchWithSource:self.easeConvsVC.dataAry searchText:aString collationStringSelector:@selector(showName) resultBlock:^(NSArray *results) {
         dispatch_async(dispatch_get_main_queue(), ^{
             if ([weakself.resultController.dataArray count] > 0) {
                 [weakself.resultController.dataArray removeAllObjects];
             }
            [weakself.resultController.dataArray addObjectsFromArray:results];
            [weakself.resultController.tableView reloadData];
        });
    }];
}
   
#pragma mark - EaseConversationsViewControllerDelegate

- (id<EaseUserDelegate>)easeUserDelegateAtConversationId:(NSString *)conversationId conversationType:(EMConversationType)type
{
    EMConversationUserDataModel *userData = [[EMConversationUserDataModel alloc]initWithEaseId:conversationId conversationType:type];
    if(type == EMConversationTypeChat) {
        if (![conversationId isEqualToString:EMSYSTEMNOTIFICATIONID]) {
            EMUserInfo* userInfo = [[UserInfoStore sharedInstance] getUserInfoById:conversationId];
            if(userInfo) {
                if([userInfo.nickName length] > 0) {
                    userData.showName = userInfo.nickName;
                }
                if([userInfo.avatarUrl length] > 0) {
                    userData.avatarURL = userInfo.avatarUrl;
                }
            }else{
                [[UserInfoStore sharedInstance] fetchUserInfosFromServer:@[conversationId]];
            }
        }
    }
    return userData;
}

- (NSArray<UIContextualAction *> *)easeTableView:(UITableView *)tableView trailingSwipeActionsForRowAtIndexPath:(NSIndexPath *)indexPath actions:(NSArray<UIContextualAction *> *)actions
{
    NSMutableArray<UIContextualAction *> *array = [[NSMutableArray<UIContextualAction *> alloc]init];
    __weak typeof(self) weakself = self;
    UIContextualAction *deleteAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleNormal
                                                                               title:NSLocalizedString(@"delete", nil)
                                                                             handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL))
    {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:NSLocalizedString(@"deletePrompt", nil) preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *clearAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"delete", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [tableView setEditing:NO];
            [self _deleteConversation:indexPath];
        }];
        [clearAction setValue:[UIColor colorWithRed:245/255.0 green:52/255.0 blue:41/255.0 alpha:1.0] forKey:@"_titleTextColor"];
        [alertController addAction:clearAction];
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style: UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [tableView setEditing:NO];
        }];
        [cancelAction  setValue:[UIColor blackColor] forKey:@"_titleTextColor"];
        [alertController addAction:cancelAction];
        alertController.modalPresentationStyle = 0;
        [weakself presentViewController:alertController animated:YES completion:nil];
    }];
    deleteAction.backgroundColor = [UIColor redColor];
    [array addObject:deleteAction];
    [array addObject:actions[1]];
    return [array copy];
}

- (void)easeTableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
        
    EaseConversationCell *cell = (EaseConversationCell*)[tableView cellForRowAtIndexPath:indexPath];
    //系统通知  
    if ([cell.model.easeId isEqualToString:EMSYSTEMNOTIFICATIONID]) {
        EMNotificationViewController *controller = [[EMNotificationViewController alloc] initWithStyle:UITableViewStylePlain];
        [self.navigationController pushViewController:controller animated:YES];
        return;
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:CHAT_PUSHVIEWCONTROLLER object:cell.model];
}

#pragma mark - EMGroupManagerDelegate
- (void)didLeaveGroup:(EMGroup *)aGroup reason:(EMGroupLeaveReason)aReason {
    [self refreshTableView];
}

#pragma mark - Action

//删除会话
- (void)_deleteConversation:(NSIndexPath *)indexPath
{
    __weak typeof(self) weakSelf = self;
    NSInteger row = indexPath.row;
    EaseConversationModel *model = [self.easeConvsVC.dataAry objectAtIndex:row];
    int unreadCount = [[EMClient sharedClient].chatManager getConversationWithConvId:model.easeId].unreadMessagesCount;
    [[EMClient sharedClient].chatManager deleteServerConversation:model.easeId conversationType:model.type isDeleteServerMessages:YES completion:^(NSString *aConversationId, EMError *aError) {
        if (aError) {
            [weakSelf showHint:aError.errorDescription];
        }
        [[EMClient sharedClient].chatManager deleteConversation:model.easeId isDeleteMessages:YES completion:^(NSString *aConversationId, EMError *aError) {
            [weakSelf.easeConvsVC.dataAry removeObjectAtIndex:row];
            [weakSelf.easeConvsVC refreshTabView];
            if (unreadCount > 0 && weakSelf.deleteConversationCompletion) {
                weakSelf.deleteConversationCompletion(YES);
            }
        }];
    }];
}

@end
